package com.up.vms.interfaces.rest.controller;

import com.up.jiasai.spring.annotation.LoginedAuth;
import com.up.vms.application.base.auth.UserSession;
import com.up.vms.application.common.utils.ExcelUtils;
import com.up.vms.application.service.ActivityApplicationService;
import com.up.vms.domain.module.ActivityDetailVO;
import com.up.vms.domain.module.ActivityUploadAdditionalInfoVO;
import com.up.vms.domain.module.ActivityUploadImageVO;
import com.up.vms.domain.vm.entity.UserActivityInfo;
import com.up.vms.infrastructure.mvc.BaseResponse;
import com.up.vms.infrastructure.mvc.GeneRespDTO;
import com.up.vms.infrastructure.mvc.RespCode;
import com.up.vms.infrastructure.mvc.ReturnCode;
import com.up.vms.infrastructure.util.CommonUtils;
import com.up.vms.interfaces.rest.request.ActivityDetailRequest;
import com.up.vms.interfaces.rest.response.CommonResponse;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@Api(value = "App活动接口", produces = "application/json")
@RequestMapping("/app/v1")
@Slf4j
public class AppActivityController {

    @Autowired
    private ActivityApplicationService activityApplicationService;


    // 活动信息 及 上传信息
    @RequestMapping(value = "/activity/{id}", method = RequestMethod.GET)
    public BaseResponse activityInfo(@PathVariable(name = "id") Long id, @LoginedAuth UserSession userSession) {
        CommonResponse response = new CommonResponse();
        try {

            GeneRespDTO geneRespDTO = activityApplicationService.getActivityInfo(id, userSession.getId());

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }

    // 上传提交
    @RequestMapping(value = "/activity/detail/upload", method = RequestMethod.POST)
    public BaseResponse activityDetailUpload(@RequestBody ActivityDetailRequest request, @LoginedAuth UserSession userSession) {
        CommonResponse response = new CommonResponse();
        try {

            ActivityDetailVO activityDetailVO = new ActivityDetailVO();
            activityDetailVO.setActivityId(request.getActivityId());
            if (CommonUtils.isNotNull(request.getImageList())) {
                List<ActivityUploadImageVO> imageList = request.getImageList();
                if (imageList != null) {
                    for (int i = 0; i < imageList.size(); i++) {
                        ActivityUploadImageVO vo = imageList.get(i);
                        vo.setSortNo(i);
                    }
                }
//                Collections.sort(imageList, Comparator.comparing(ActivityUploadImageVO::getSortNo));
                activityDetailVO.setImageList(imageList);
            }
            if (CommonUtils.isNotNull(request.getAdditionalInfoList())) {
                List<ActivityUploadAdditionalInfoVO> additionalInfoList = request.getAdditionalInfoList();
                if (additionalInfoList != null) {
                    for (int i = 0; i < additionalInfoList.size(); i++) {
                        ActivityUploadAdditionalInfoVO vo = additionalInfoList.get(i);
                        vo.setSortNo(i);
                    }
                }
//                Collections.sort(additionalInfoList, Comparator.comparing(ActivityUploadAdditionalInfoVO::getSortNo));
                activityDetailVO.setAdditionalInfoList(additionalInfoList);
            }

            GeneRespDTO geneRespDTO = activityApplicationService.uploadDetail(activityDetailVO, userSession.getId());

            response.setRespCode(geneRespDTO.getRespCode());
            response.setData(geneRespDTO.getData());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        }

        return response;
    }


    @RequestMapping("/importExcel")
    public BaseResponse importExcel(@RequestParam(value = "file") MultipartFile file,
                                    @RequestParam(value = "activityId") Long activityId,
                                    @RequestParam(value = "reset", required = false) Integer reset) {
        CommonResponse response = new CommonResponse();

//        String token = getRequest().getHeader("Authorization");
//        String key = String.format(CacheKeyConstants.ADMIN_OPEN_ID_KEY, token);
//        AdminSession adminSession = cacheService.get(key, AdminSession.class);

//        if (adminSession == null || adminSession.getAdminId() == null) {
//            return sendError("请登录");
//        }

        if (file == null || file.isEmpty()) {
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR.getCode(), "请选择表格"));
        }
        InputStream is = null;
        try {

            is = file.getInputStream();
            //获取文件名
            String fileName = file.getOriginalFilename();

            //根据版本选择创建Workbook的方式
            Workbook wb = null;
            Sheet sheetAt = null;
            //根据文件名判断文件是2003版本还是2007版本
            if (ExcelUtils.isExcel2007(fileName)) {
                wb = new XSSFWorkbook(is);
                sheetAt = wb.getSheetAt(0);
            } else {
                wb = new HSSFWorkbook(is);
                sheetAt = wb.getSheetAt(0);
            }

            List<UserActivityInfo> users = new ArrayList<>();

            for (Row row : sheetAt) {
                int rowNum = row.getRowNum();
                if (rowNum == 0) {
                    continue;
                }

                Cell cell0 = row.getCell(0);
                String userName = null;
                if (cell0 != null) {
                    cell0.setCellType(CellType.STRING);
                    userName = cell0.getStringCellValue();//用户名
                }

                Cell cell1 = row.getCell(1);
                String idNumber = null;
                if (cell1 != null) {
                    cell1.setCellType(CellType.STRING);
                    idNumber = cell1.getStringCellValue();
                }

                Cell cell2 = row.getCell(2);
                String userPhone = null;
                if (cell2 != null) {
                    cell2.setCellType(CellType.STRING);
                    userPhone = cell2.getStringCellValue();//手机号
                }

                Cell cell3 = row.getCell(3);
                String cardNo = null;
                if (cell3 != null) {
                    cell3.setCellType(CellType.STRING);
                    cardNo = cell3.getStringCellValue();
                }

                Cell cell4 = row.getCell(4);
                String bankCardNo = null;
                if (cell4 != null) {
                    cell4.setCellType(CellType.STRING);
                    bankCardNo = cell4.getStringCellValue();
                }

                Cell cell5 = row.getCell(5);
                Double amount = 0.0;
                if (cell5 != null) {
                    cell5.setCellType(CellType.NUMERIC);
                    amount = cell5.getNumericCellValue();//工作单位
                }

                if (CommonUtils.isNotNull(userPhone) && CommonUtils.isNotNull(idNumber)) {
                    UserActivityInfo user = new UserActivityInfo();
                    user.setUserName(userName);
                    user.setUserPhone(userPhone);
                    user.setIdNumber(idNumber);
                    user.setCardNo(cardNo);
                    user.setBankCardNo(bankCardNo);
                    user.setAmount(BigDecimal.valueOf(amount));
                    user.setActivityId(activityId);

                    users.add(user);
                }

            }

            if (!users.isEmpty()) {
                GeneRespDTO geneRespDTO = activityApplicationService.saveUsers(users, activityId, reset == 1);

                response.setRespCode(geneRespDTO.getRespCode());
            }

        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
            response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    log.error(ex.getMessage(), ex);
                    response.setRespCode(new RespCode(ReturnCode.SERVICE_ERROR));
                }
            }
        }

        return response;
    }

}
